package com.mouse.hxsj.service;

import com.mouse.damo.micro.Com;
import com.mouse.damo.micro.Press;
import com.mouse.damo.micro.Sleep;
import com.mouse.hxsj.dao.GameSkillMapper;
import com.mouse.hxsj.entity.enums.ActionEnum;
import com.mouse.hxsj.entity.enums.SkillKeyEnum;
import com.mouse.hxsj.entity.po.GameSkill;
import com.mouse.hxsj.entity.po.SkillAction;
import com.mouse.hxsj.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 定时器-执行脚本
 */
@Slf4j
@Component
public class TimerService extends TimerTask {
    private Com com;
    private Integer skillId;
    private Long delay;
    private Timer timer;
    @Autowired
    private GameSkillMapper gameSkillMapper;

    public void schedule(Com com, Integer skillId, Date date, Long delay) {
        log.info("开始定时器");
        this.com = com;
        this.skillId = skillId;
        this.delay = delay;
        if (date == null && delay == null) {
            log.info("参数w为空,非定时器");
            new Thread(() -> run()).start();
            return;
        }
        timer = new Timer();
        if (date == null) {
            timer.schedule(this, delay);
        } else if (delay == null) {
            timer.schedule(this, date);
        } else {
            timer.schedule(this, date, delay);
        }
    }

    @Override
    public void run() {
        GameSkill gameSkill = gameSkillMapper.selectById(skillId);
        String skillKeys = gameSkill.getSkillKeys();
        List<SkillAction> skillActionList = JsonUtil.getObjectList(skillKeys, SkillAction.class);
        Collections.sort(skillActionList, (o1, o2) -> o1.getIndex() - o2.getIndex());
        Press press = new Press(com);
        press.groupPress(Press.ALT,Press.A);
        skillActionList.forEach(skillAction -> {
            SkillKeyEnum skillKey = skillAction.getSkillKey();
            int key1 = skillKey.getKey1();
            int key2 = skillKey.getKey2();
            if (key2 == 0 && key1 == 0) {
                ActionEnum action = skillKey.getAction();
                action.exec(com);
            } else if (key2 == 0) {
                press.keyPress(key1);
            } else {
                press.groupPress(key1, key2);
            }
            Sleep.sleep(skillAction.getSleep() * 1000);
        });
        if (delay == null && timer != null) {
            timer.cancel();
        }
        log.info("定时器结束");
    }
}
